package com.rzico.sbl.ui.report.manager

import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.github.mikephil.extend.setChartValueSelectedListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportThirdBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.model.ManagerGoodsData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.ReportThirdViewModel
import com.xinnuo.common.extend.get
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems

class ReportThirdActivity : BaseActivity(R.layout.activity_report_third) {

    private val mBinding by lazy { ActivityReportThirdBinding.bind(getRootView()) }

    private val mGoodsList = ArrayList<ManagerGoodsData>()
    private val mRangeList = ArrayList<ManagerDate>()
    private var mProductSn = ""
    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()

    override fun getViewModel() = get<ReportThirdViewModel>()

    override fun initData() {
        initTitle("商品统计")

        initLayout()

        getBrandData()
    }

    private fun initLayout() {
        mBinding.also {
            it.thirdGoods1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    xTextSize = 8f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mGoodsList.indices) ""
                    else mGoodsList[value.toInt()].name
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductSn = mGoodsList[index].sn
                        mBinding.thirdGoodsTitle.text = mGoodsList[index].name
                        getRangeData()
                    }
                }
            }

            it.thirdGoods2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mRangeList.indices) ""
                    else mRangeList[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.thirdGoodsTime.addTimeListener { start, end, _ ->
                mBeginDate = start
                mEndDate = end

                getViewModel().cancelRequest()
                getBrandData()
            }
        }
    }

    /**
     * 设置所有商品销量柱状图数据
     */
    private fun setBrandData() {
        mGoodsList.sumOf {
            it.quantity.intValue
        }.apply {
            mBinding
                .thirdGoodsTotal
                .text = if (this > 0) " (总: ${this})" else ""
        }

        mBinding
            .thirdGoods1
            .apply {
                if (mGoodsList.isEmpty()) {
                    clear()
                    mBinding.thirdGoods2.clear()
                    mBinding.thirdGoodsTitle.text = "暂无商品"
                } else {
                    setSingleData(
                        entries = mGoodsList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.quantity.toFloat())
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置单个商品销量柱状图数据
     */
    private fun setGoodsData() {
        mBinding
            .thirdGoods2
            .apply {
                setSingleData(
                    entries = mRangeList.mapIndexed { index, data ->
                        BarEntry(index.toFloat(), data.quantity.toFloat())
                    },
                    colorList = listOf(
                        getViewModel()
                            .brandColor()[
                                mGoodsList.indexOfFirst { it.sn == mProductSn } % 24
                            ]
                    ),
                    isHighlight = false,
                    formatter = CustomValueFormatter()
                )

                animateY(500)
            }
    }

    /**
     * 获取所有商品销量
     */
    private fun getBrandData() {
        getViewModel()
            .goodsBrandList(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mGoodsList.clear()
                    mGoodsList.addItems(list)

                    setBrandData()

                    if (mGoodsList.isNotEmpty()) {
                        if (mGoodsList.none { it.sn == mProductSn }) {
                            mProductSn = mGoodsList[0].sn
                            mBinding.thirdGoodsTitle.text = mGoodsList[0].name
                        }
                        getRangeData()
                    }
                }
            )
    }

    /**
     * 获取单个商品最近销量
     */
    private fun getRangeData() {
        getViewModel()
            .goodsSaleList(
                goodsSn = mProductSn,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mRangeList.clear()
                    mRangeList.addItems(it)

                    setGoodsData()
                }
            )
    }

}